<template>
  <h3>基本信息</h3>
  <ContentWrap>
    <el-table :data="roomDetails">
      <el-table-column label="房间号" prop="number" min-width="120"/>
      <el-table-column label="类型" prop="typeName" min-width="100"/>
      <el-table-column label="教学楼" prop="buildingName" min-width="120"/>
      <el-table-column label="楼层" prop="floor"/>
      <el-table-column label="电量" prop="battery"/>
      <el-table-column :width="400" align="center" label="操作" fixed="right">
        <template #default="scope">
          <div class="button-container">
            <el-button v-hasPermi="['yxt:room:door:remote']" plain type="primary" @click="onRemote">
              远程开门
            </el-button>
            <el-button v-hasPermi="['yxt:room:open']" plain type="primary"
                       @click="onOpen('确认开启所选琴房?', false)">
              开启空间
            </el-button>
            <el-button v-hasPermi="['yxt:room:close']" plain type="danger" :disabled="isClose"
                       @click="onClose">
              关闭空间
            </el-button>
            <el-button v-hasPermi="['yxt:room:lock']" plain type="warning" :disabled="isLock"
                       @click="onLock">
              锁定空间
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>


  <h3>其他信息</h3>
  <div class="tabs-container">
    <el-tabs v-model="activeName" class="full-width-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="专属人管理" name="first">
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px"
                 label-width="55px" @submit.native.prevent>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" class="!w-150px" clearable placeholder="请输入姓名"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="queryParams.mobile" class="!w-150px" clearable
                      placeholder="请输入手机号"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="状态" prop="isValid">
            <el-select v-model="queryParams.isValid" placeholder="请选择状态" clearable
                       class="!w-150px">
              <el-option v-for="item in isValids" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search"/>
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh"/>
              重置
            </el-button>
            <el-button type="warning" plain @click="handleImport">
              <Icon icon="ep:upload"/>
              手动导入
            </el-button>
            <el-button type="warning" plain @click="handleStuImportExcel()">
              <Icon icon="ep:upload"/>
              导入学生
            </el-button>
            <el-button type="warning" plain @click="handleTeaImportExcel()">
              <Icon icon="ep:upload"/>
              导入教师
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 分隔元素 -->
        <div style="margin-bottom: 15px;"></div>
        <el-table :data="list" v-loading="loading" style="width: 100%">
          <el-table-column prop="name" label="用户姓名"/>
          <el-table-column prop="mobile" label="用户手机号"/>
          <el-table-column label="类型">
            <template #default="scope">
              <span v-if="scope.row.memberType === 0">学生</span>
              <span v-if="scope.row.memberType === 1">教师</span>
            </template>
          </el-table-column>
          <el-table-column label="可使用日期" align="center" width="300px">
            <template #default="scope">
               <span v-if="scope.row.availableStartDate && scope.row.availableEndDate">
                {{ scope.row.availableStartDate }} 至 {{ scope.row.availableEndDate }}
               </span>
              <span v-else>全时段</span>
            </template>
          </el-table-column>
          <!-- 可使用周期 -->
          <el-table-column prop="availableWeek" label="可使用周期">
            <template #default="scope">
               <span v-if="scope.row.availableWeek">
                {{ formatAvailableWeek(scope.row.availableWeek) }}
              </span>
              <span v-else>全时段</span>
            </template>
          </el-table-column>
          <!-- 可使用时间段 -->
          <el-table-column prop="availableTime" label="可使用时间段">
            <template #default="scope">
              <span v-if="scope.row.availableTime">
                {{ formatAvailableTime(scope.row.availableTime) }}
              </span>
              <span v-else>全时段</span>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <span v-if="scope.row.isValid === 1">未过期</span>
              <span v-if="scope.row.isValid === 2">已过期</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150px">
            <template #default="scope">
              <el-space>
                <el-button @click="handleExclusiveEdit(scope.row)" type="primary" size="small">
                  编辑
                </el-button>
                <!--todo 删除逻辑 需要确认-->
                <el-button @click="handleExclusiveDelete(scope.row)" type="danger" size="small">
                  删除
                </el-button>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo"
                    :total="total" @pagination="getList"/>
      </el-tab-pane>

      <!--   禁用日期管理   -->
      <el-tab-pane label="禁用日期管理" name="second">
        <el-form-item>
          <el-button type="primary" plain @click="handleExclusiveBanAdd">
            <Icon class="mr-5px" icon="ep:plus"/>
            新增
          </el-button>
        </el-form-item>
        <el-table :data="banList" v-loading="banLoading" style="width: 100%">
          <el-table-column prop="banStartTime" label="禁用开始日期"/>
          <el-table-column prop="banEndTime" label="禁用结束日期"/>
          <el-table-column label="操作" align="center" width="150px">
            <template #default="scope">
              <el-space>
                <!--todo 删除逻辑 需要确认-->
                <el-button @click="handleBanDelete(scope.row)" type="danger" size="small">删除
                </el-button>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
        <Pagination v-model:limit="baseQueryParams.pageSize" v-model:page="baseQueryParams.pageNo"
                    :total="banTotal" @pagination="getBanList"/>
      </el-tab-pane>

      <!-- 密码管理 -->
      <el-tab-pane label="密码管理" name="third">
        <el-form-item>
          <el-button type="primary" plain @click="handleExclusivePasswordAdd">
            <Icon class="mr-5px" icon="ep:plus"/>
            新增密码
          </el-button>
        </el-form-item>
        <el-table :data="passwordList" v-loading="passwordLoading" style="width: 100%">
          <el-table-column prop="password" label="密码"/>
          <el-table-column label="密码有效期" align="center" width="300px">
            <template #default="scope">
               <span v-if="scope.row.availableStartTime && scope.row.availableEndTime">
                {{ scope.row.availableStartTime }} 至 {{ scope.row.availableEndTime }}
               </span>
            </template>
          </el-table-column>
          <el-table-column :formatter="dateFormatter" prop="createTime" label="创建时间"/>
          <el-table-column prop="remark" label="备注"/>
          <el-table-column label="操作" align="center" width="150px">
            <template #default="scope">
              <el-space>
                <!--todo 删除逻辑 需要确认-->
                <el-button @click="handleExclusivePasswordDelete(scope.row)" type="danger"
                           size="small">
                  删除
                </el-button>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
        <Pagination v-model:limit="baseQueryParams.pageSize" v-model:page="baseQueryParams.pageNo"
                    :total="passwordTotal" @pagination="getPasswordList"/>
      </el-tab-pane>

      <!--  开门记录    -->
      <el-tab-pane label="开门记录" name="fourth">
        <el-form ref="openQueryFormRef" :inline="true" :model="openQueryParams" class="-mb-15px"
                 label-width="100px" @submit.native.prevent>
          <el-form-item label="开门人姓名" prop="name">
            <el-input v-model="openQueryParams.name" class="!w-200px" clearable
                      placeholder="请输入姓名"
                      @keyup.enter="handleOpenQuery"/>
          </el-form-item>
          <el-form-item label="开门人手机号" prop="mobile">
            <el-input v-model="openQueryParams.mobile" class="!w-200px" clearable
                      placeholder="请输入手机号"
                      @keyup.enter="handleOpenQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleOpenQuery">
              <Icon class="mr-5px" icon="ep:search"/>
              搜索
            </el-button>
            <el-button @click="resetOpemQuery">
              <Icon class="mr-5px" icon="ep:refresh"/>
              重置
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 分隔元素 -->
        <div style="margin-bottom: 15px;"></div>
        <el-table :data="openList" v-loading="openLoading" style="width: 100%">
          <el-table-column :formatter="dateFormatter" prop="createTime" label="开门时间"/>
          <el-table-column label="类型">
            <template #default="scope">
              <span v-if="scope.row.type === 1">远程开门</span>
              <span v-if="scope.row.type === 2">蓝牙开门</span>
            </template>
          </el-table-column>
          <el-table-column label="开门人姓名">
            <template #default="scope">
              <span v-if="scope.row.memberType !== 2">{{ scope.row.name }}</span>
              <span v-if="scope.row.memberType === 2">{{ scope.row.adminName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="开门人类型">
            <template #default="scope">
              <span v-if="scope.row.memberType === 0">学生</span>
              <span v-if="scope.row.memberType === 1">教师</span>
              <span v-if="scope.row.memberType === 2">后台用户</span>
            </template>
          </el-table-column>
          <el-table-column label="开门人手机号">
            <template #default="scope">
              <span v-if="scope.row.memberType !== 2">{{ scope.row.mobile }}</span>
              <span v-if="scope.row.memberType === 2">{{ scope.row.adminMobile }}</span>
            </template>
          </el-table-column>
        </el-table>
        <Pagination v-model:limit="openQueryParams.pageSize" v-model:page="openQueryParams.pageNo"
                    :total="openTotal" @pagination="getOpenList"/>
      </el-tab-pane>

      <!--  今日订单    -->
      <el-tab-pane label="今日订单" name="fifth">
        <el-form ref="subscribeQueryFormRef" :inline="true" :model="subscribeQueryParams"
                 class="-mb-15px"
                 label-width="100px" @submit.native.prevent>
          <el-form-item label="预约人姓名" prop="name">
            <el-input v-model="subscribeQueryParams.name" class="!w-200px" clearable
                      placeholder="请输入姓名"
                      @keyup.enter="handleSubscribeQuery"/>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="subscribeQueryParams.mobile" class="!w-200px" clearable
                      placeholder="请输入手机号"
                      @keyup.enter="handleSubscribeQuery"/>
          </el-form-item>
          <el-form-item label="归属学校" prop="schoolId" v-if="tenantId == 1">
            <el-select v-model="subscribeQueryParams.schoolId" placeholder="请选择学校"
                       class="!w-200px" filterable default-first-option clearable>
              <el-option v-for="item in schools" :key="item.id" :label="item.name"
                         :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预约状态" prop="status">
            <el-select v-model="subscribeQueryParams.status" placeholder="请选择预约状态" clearable
                       class="!w-200px">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YXT_SUBSCRIBE_STATUS)"
                         :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预约时间" prop="subscribeTime">
            <el-date-picker unlink-panels v-model="subscribeQueryParams.subscribeTime"
                            value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
                            start-placeholder="起始日期" end-placeholder="结束日期"
                            class="!w-200px"/>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleSubscribeQuery">
              <Icon class="mr-5px" icon="ep:search"/>
              搜索
            </el-button>
            <el-button @click="resetSubscribeQuery">
              <Icon class="mr-5px" icon="ep:refresh"/>
              重置
            </el-button>
            <el-button type="danger" @click="cancel" :disabled="isEmpty(selectKeys)">
              取消预约
            </el-button>
            <el-button type="success" plain @click="handleSubscribeExport" :loading="exportLoading">
              <Icon icon="ep:download"/>
              导出
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 分隔元素 -->
        <div style="margin-bottom: 15px;"></div>
        <el-table :data="subscribeList" v-loading="subscribeLoading" style="width: 100%"
                  @selection-change="selectionChange">
          <el-table-column type="selection"/>
          <el-table-column label="头像" prop="avatar" width="50">
            <template #default="scope">
              <div style="width: 36px; height: 36px">
                <el-image v-if="scope.row.avatar" :src="scope.row.avatar"
                          :preview-src-list="[scope.row.avatar]" preview-teleported
                          hide-on-click-modal/>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="预约人姓名" align="center" min-width="150"/>
          <el-table-column label="归属学校" prop="schoolName" align="center" min-width="150"/>
          <el-table-column prop="mobile" label="手机号" align="center" min-width="150"/>
          <el-table-column label="类型" prop="type" align="center">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.YXT_USER_TYPE" :value="scope.row.memberType"/>
            </template>
          </el-table-column>
          <el-table-column :formatter="dateFormatter" label="预约时间" prop="startTime"
                           min-width="180" align="center"/>
          <el-table-column label="预约时长" prop="keepTime" align="center" min-width="150"/>
          <el-table-column label="实际时长" prop="actualTime" align="center" min-width="150"/>
          <el-table-column label="预约状态" prop="status" align="center">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.YXT_SUBSCRIBE_STATUS" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column :formatter="dateFormatter" align="center" label="创建时间"
                           prop="createTime"
                           min-width="180"/>
        </el-table>
        <Pagination v-model:limit="subscribeQueryParams.pageSize"
                    v-model:page="subscribeQueryParams.pageNo"
                    :total="subscribeTotal" @pagination="getSubscribeList"/>
      </el-tab-pane>
    </el-tabs>
  </div>

  <!-- 关闭和锁定原因输入弹框 -->
  <Dialog v-model="dialog.visible" title="" width="360">
    <el-form ref="dialogFormRef" :model="dialog">
      <el-form-item label="操作原因" prop="reason"
                    :rules="[{required: true, message: '请输入原因', trigger: ['blur', 'change']}]">
        <el-input v-model="dialog.reason" placeholder="请输入原因"/>
      </el-form-item>
      <el-form-item v-if="dialog.actionType === 'lock'" label="锁定时间" prop="lockDate"
                    :rules="[{required: true, message: '请选择锁定时间', trigger: ['blur', 'change']}]">
        <el-date-picker v-model="dialog.lockDate" unlink-panels placeholder="请选择时间" type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="handleDialogSubmit">确 定</el-button>
      <el-button @click="handleDialogCancel">取 消</el-button>
    </template>
  </Dialog>

  <!-- 编辑专属人信息弹框 -->
  <Dialog v-model="exclusiveDialog.exclusiveVisible" title="编辑" width="800">
    <el-form ref="exclusiveDialogFormRef" :model="exclusiveDialog">
      <!-- 日期选择 -->
      <el-form-item label="可使用日期" prop="dateTime">
        <el-date-picker
          v-model="exclusiveDialog.dateTime"
          unlink-panels
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-380px"/>
      </el-form-item>

      <!-- 周几选择 -->
      <el-form-item label="可使用周期" prop="availableWeek">
        <el-checkbox-group v-model="exclusiveDialog.availableWeek">
          <el-checkbox v-for="day in weekdays" :label="day.value" :key="day.value">
            {{ day.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 时间段选择 -->
      <el-form-item label="可使用时间段" prop="timeRanges">
        <div class="time-picker-wrapper">
          <!-- 迭代所有时间段 -->
          <div v-for="(timeRange, index) in timeRangesLocal" :key="index" class="time-picker-item">
            <el-time-picker
              v-model="timeRangesLocal[index]"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              class="!w-380px"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="delete-button"
              @click="removeTimeRange(index)"
            >
              删除
            </el-button>
          </div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            class="add-button"
            @click="addTimeRange"
          >
            添加时间段
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleExclusiveDialogSubmit">确 定</el-button>
      <el-button @click="handleExclusiveDialogCancel">取 消</el-button>
    </template>
  </Dialog>

  <!-- 批量导入弹框 -->
  <Dialog v-model="importDialog.importVisible" title="导入" width="800"
          @close="handleImportDialogClose">
    <el-form ref="importDialogFormRef" :model="importDialog" :rules="importFormRules">
      <el-form-item label="类型" prop="memberType">
        <el-select v-model="importDialog.memberType" placeholder="请选择类型" clearable
                   @change="fetchOptions"
                   class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YXT_USER_TYPE)" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>

<!--      <el-form-item label="用户" prop="memberIds">-->
<!--        <el-select v-model="importDialog.memberIds" placeholder="请选择用户" clearable filterable-->
<!--                   multiple>-->
<!--          <el-option v-for="member in memberOptions" :key="member.id" :label="member.name"-->
<!--                     :value="member.id"/>-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="用户" prop="memberIds">
        <el-select v-model="importDialog.memberIds" placeholder="请选择用户" clearable filterable multiple>
          <el-option
            v-for="member in memberOptions"
            :key="member.id"
            :label="`${member.name} - ${member.mobile}`"
          :value="member.id"
          />
        </el-select>
      </el-form-item>

      <el-form ref="importDialogFormRef" :model="importDialog">
        <!-- 日期选择 -->
        <el-form-item label="可使用日期" prop="dateTime">
          <el-date-picker
            v-model="importDialog.dateTime"
            unlink-panels
            value-format="YYYY-MM-DD"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="!w-380px"/>
        </el-form-item>

        <!-- 周几选择 -->
        <el-form-item label="可使用周期" prop="availableWeek">
          <el-checkbox-group v-model="importDialog.availableWeek">
            <el-checkbox v-for="day in weekdays" :label="day.value" :key="day.value">
              {{ day.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 时间段选择 -->
        <el-form-item label="可使用时间段" prop="timeRanges">
          <div class="time-picker-wrapper">
            <!-- 迭代所有时间段 -->
            <div v-for="(timeRange, index) in timeRangesLocal" :key="index"
                 class="time-picker-item">
              <el-time-picker
                v-model="timeRangesLocal[index]"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
                class="!w-380px"
              />
              <el-button
                type="danger"
                icon="el-icon-delete"
                class="delete-button"
                @click="removeTimeRange(index)"
              >
                删除
              </el-button>
            </div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              class="add-button"
              @click="addTimeRange"
            >
              添加时间段
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleImportDialogSubmit">确 定</el-button>
      <el-button @click="handleImportDialogClose">取消</el-button>
    </template>
  </Dialog>

  <!-- 新增专属空间禁用日期弹框 -->
  <Dialog v-model="exclusiveBanDialog.exclusiveBanVisible" title="新增" width="800">
    <el-form ref="exclusiveBanDialogFormRef" :model="exclusiveBanDialog">
      <!-- 日期选择 -->
      <el-form-item label="可使用日期" prop="dateTime">
        <el-date-picker
          v-model="exclusiveBanDialog.dateTime"
          unlink-panels
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-380px"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleExclusiveBanDialogSubmit">确 定</el-button>
      <el-button @click="handleExclusiveBanDialogCancel">取 消</el-button>
    </template>
  </Dialog>

  <!-- 新增专属空间密码弹框 -->
  <Dialog v-model="exclusivePasswordDialog.exclusivePasswordVisible" title="新增" width="800">
    <el-form ref="exclusivePasswordDialogFormRef" :model="exclusivePasswordDialog" :rules="passwordFormRules">
      <el-form-item label="密码" prop="password">
        <el-input v-model="exclusivePasswordDialog.password" placeholder="请输入密码"/>
      </el-form-item>
      <!-- 日期选择 -->
      <el-form-item label="密码有效期" prop="dateTime">
        <el-date-picker
          v-model="exclusivePasswordDialog.dateTime"
          unlink-panels
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-380px"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="exclusivePasswordDialog.remark" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleExclusivePasswordDialogSubmit">确 定</el-button>
      <el-button @click="handleExclusivePasswordDialogCancel">取 消</el-button>
    </template>
  </Dialog>

  <MemberStuImportForm ref="importStuFormRef" @success="getList"/>
  <MemberTeaImportForm ref="importTeaFormRef" @success="getList"/>

</template>
<script lang="ts" setup>
import * as RoomApi from "@/api/yxt/room";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {useConfirm, useMessage} from "@/components/Notice";
import {ref} from 'vue'
import {FormInstance, TabsPaneContext} from 'element-plus'
import {isEmpty} from "lodash-es";
import {getTenantId} from "@/utils/auth";
import {
  useRoomApi,
  useRoomExclusiveApi,
  useRoomExclusiveBanApi, useRoomExclusiveOpenApi,
  useRoomPasswordApi
} from "@/api/yxt/room";
import {useMemberApi} from "@/api/yxt/member";
import MemberStuImportForm from "@/views/yxt/room/exclusive/MemberStuImportForm.vue";
import MemberTeaImportForm from "@/views/yxt/room/exclusive/MemberTeaImportForm.vue";
import {dateFormatter} from "@/utils/formatTime";
import {useSubscribeApi} from "@/api/yxt/subscribe";
import * as XLSX from 'xlsx/dist/xlsx.full.min'
import {useSchoolApi} from "@/api/yxt/school";

defineOptions({name: 'YxtRoomExclusiveDetail'})

const {t} = useI18n() // 国际化
const route = useRoute() // 路由

const roomApi = useRoomApi();
const memberApi = useMemberApi();
const roomExclusiveApi = useRoomExclusiveApi();
const roomExclusiveBanApi = useRoomExclusiveBanApi();
const roomPasswordApi = useRoomPasswordApi();
const roomExclusiveOpenApi = useRoomExclusiveOpenApi();
const schoolApi = useSchoolApi();
const subscribeApi = useSubscribeApi();
const roomDetails = ref<Array<any>>([]) //房间详细信息
const dialogFormVisible = ref(false)
const queryFormRef = ref()
const openQueryFormRef = ref()
const subscribeQueryFormRef = ref()
const isClose = ref(false)
const isLock = ref(false)
const selectKeys = ref<Array<any>>([])
const dialogFormRef = ref<FormInstance>();
const exclusiveDialogFormRef = ref<FormInstance>();
const exclusiveBanDialogFormRef = ref<FormInstance>();
const exclusivePasswordDialogFormRef = ref<FormInstance>();
const importDialogFormRef = ref<FormInstance>();
const lock = ref<any>({
  visible: false
})
const tenantId = getTenantId();
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const banList = ref([]) // 禁用日期列表的数据
const banLoading = ref(true) // 列表的加载中
const banTotal = ref(0) // 列表的总页数
const passwordList = ref([]) // 密码列表的数据
const passwordLoading = ref(true) // 列表的加载中
const passwordTotal = ref(0)// 列表的总页数
const openList = ref([]) // 开门记录列表数据
const openLoading = ref(true)// 列表的加载中
const openTotal = ref(0)// 列表的总页数
const subscribeList = ref([]) // 开门记录列表数据
const subscribeLoading = ref(true)// 列表的加载中
const subscribeTotal = ref(0)// 列表的总页数
const memberOptions = ref([]); // 用户数据
const importStuFormRef = ref()
const importTeaFormRef = ref()
const schools = ref<Array<any>>([])
const multipleSelection = ref<Array<any>>([])
const exportLoading = ref(false)
const isDateTimeRequire = ref(false)// 密码有效期是否必填

const initParams = reactive({
  roomId: route.params.roomId
})

const isValids = ref([
  {name: "未过期", id: 1},
  {name: "已过期", id: 2}
])

// 周几选择
const weekdays = [
  {label: '周一', value: 1},
  {label: '周二', value: 2},
  {label: '周三', value: 3},
  {label: '周四', value: 4},
  {label: '周五', value: 5},
  {label: '周六', value: 6},
  {label: '周日', value: 7}
];

const weekdaysMap = {
  1: '周一',
  2: '周二',
  3: '周三',
  4: '周四',
  5: '周五',
  6: '周六',
  7: '周日',
};

// 专属人信息编辑：弹框数据
const exclusiveDialog = ref({
  id: undefined,
  exclusiveVisible: false,
  dateTime: [],
  availableWeek: [],
  timeRanges: [[]]  // 默认添加一个时间段
});

// 专属空间禁用新增：弹框数据
const exclusiveBanDialog = ref({
  roomId: initParams.roomId,
  exclusiveBanVisible: false,
  dateTime: []
});

// 专属空间密码新增：弹框数据
const exclusivePasswordDialog = ref({
  roomId: initParams.roomId,
  exclusivePasswordVisible: false,
  dateTime: [],
  password: undefined,
  remark: undefined
})

// 批量导入弹框
const importDialog = ref({
  roomId: undefined,
  importVisible: false,
  memberIds: [],
  dateTime: [],
  availableWeek: [],
  timeRanges: [[]]  // 默认添加一个时间段
})

// 将 availableWeek 数组转换为中文的星期表示
const formatAvailableWeek = (availableWeek) => {
  const weekArray = JSON.parse(availableWeek); // 将字符串转换为数组
  if (Array.isArray(weekArray)) {
    return weekArray.map(day => weekdaysMap[day]).join(', ');
  }
  return ''; // 如果 availableWeek 不是有效的数组，返回空字符串
};

// 将 availableTime 数组转换为时间范围表示
const formatAvailableTime = (availableTime) => {
  // 将单引号替换为双引号，并在字符串外添加双引号
  const normalizedTime = availableTime
    .replace(/(\d{2}:\d{2})/g, '"$1"')
    .replace(/'/g, '"');

  const timeArray = JSON.parse(normalizedTime);
  if (Array.isArray(timeArray)) {
    return timeArray.map(timeRange => timeRange.join(' - ')).join(', ');
  }
  return '';
};

// 初始化时间段为一个空数组
const timeRangesLocal = ref([]); // 初始化为 null

// 添加时间段
const addTimeRange = () => {
  if (timeRangesLocal.value === null) {
    // 如果 timeRangesLocal 为 null，初始化为一个空数组
    timeRangesLocal.value = [];
  }
  // 检查是否已经有时间段，并且最后一个时间段是空的（即 [null, null]）
  const lastRange = timeRangesLocal.value[timeRangesLocal.value.length - 1];
  if (lastRange && (lastRange[0] === null || lastRange[1] === null)) {
    // 提示用户需要填写第一个时间段
    alert('请先填写完整的时间段后再添加新的时间段');
    return;
  }
  timeRangesLocal.value.push([null, null]); // 新增独立时间段
};

// 删除时间段
const removeTimeRange = (index) => {
  if (timeRangesLocal.value.length > 1) {
    // 如果有多个时间段，删除指定的时间段
    timeRangesLocal.value.splice(index, 1);
  } else {
    // 如果只有一个时间段，删除它并将 timeRangesLocal 设置为 null
    timeRangesLocal.value = null;
  }
};

// 提交表单
const handleExclusiveDialogSubmit = async () => {
  // 更新弹框数据
  exclusiveDialog.value.timeRanges = timeRangesLocal.value ? [...timeRangesLocal.value] : null;
  // 调用 API 提交数据
  await roomExclusiveApi.edit(exclusiveDialog.value);
  // 显示成功消息
  useMessage(t('common.updateSuccess'));
  // 关闭弹框
  exclusiveDialog.value.exclusiveVisible = false;
  // 刷新数据
  await getList(); // 调用刷新数据的函数
};

// 取消表单
const handleExclusiveDialogCancel = () => {
  exclusiveDialog.value.exclusiveVisible = false;
};

// 提交新增专属空间禁用日期表单
const handleExclusiveBanDialogSubmit = async () => {
  await roomExclusiveBanApi.add(exclusiveBanDialog.value);
  useMessage(t('common.createSuccess'));
  exclusiveBanDialog.value.exclusiveBanVisible = false;
  exclusiveBanDialog.value = {
    exclusiveBanVisible: false,
    dateTime: []
  };
  await getBanList();
}

// 取消表单
const handleExclusiveBanDialogCancel = () => {
  exclusiveBanDialog.value.exclusiveBanVisible = false;
};

// 提交专属空间新增密码表单
const handleExclusivePasswordDialogSubmit = async () => {
  exclusivePasswordDialogFormRef.value?.validate(async (valid: any)=>{
    if (valid) {
      exclusivePasswordDialog.value.roomId = initParams.roomId;
      let resultMsg = await roomPasswordApi.add(exclusivePasswordDialog.value);
      useMessage(resultMsg == null ? t('common.createSuccess') : resultMsg);
      exclusivePasswordDialog.value.exclusivePasswordVisible = false;
      exclusivePasswordDialog.value = {
        exclusivePasswordVisible: false,
        dateTime: [],
        password: undefined,
        remark: undefined
      };
      await getPasswordList();
    }
  })
}

// 取消表单
const handleExclusivePasswordDialogCancel = () => {
  exclusivePasswordDialog.value.exclusivePasswordVisible = false;
}

const handleImportDialogSubmit = async () => {
  importDialogFormRef.value?.validate(async (valid: any) => {
    if (valid) {
      const lastRange = timeRangesLocal.value[timeRangesLocal.value.length - 1];
      if (lastRange && (lastRange[0] === null || lastRange[1] === null)) {
        alert('可使用时间段不合规');
        return;
      }
      // 更新弹框数据
      importDialog.value.timeRanges = [...timeRangesLocal.value];
      importDialog.value.roomId = initParams.roomId;
      await roomExclusiveApi.importData(importDialog.value);
      // 显示成功消息
      useMessage(t('common.createSuccess'));

      handleImportDialogClose(); // 提交后关闭弹框并重置表单
      // 刷新数据
      await getList(); // 调用刷新数据的函数
    }
  });

};

// 取消批量导入表单
const handleImportDialogClose = () => {
  if (importDialogFormRef.value) {
    importDialogFormRef.value.resetFields(); // 重置表单
  }
  importDialog.value = {
    importVisible: false,
    memberIds: [],
    dateTime: [],
    availableWeek: [],
    timeRanges: [[]], // 重置为初始状态
  };
  timeRangesLocal.value = []; // 重置 timeRangesLocal
  importDialog.value.importVisible = false; // 关闭弹框
};

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  roomId: initParams.roomId,
  name: '',
  mobile: '',
  isValid: undefined
})

const baseQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  roomId: initParams.roomId
})

const openQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  mobile: '',
  roomId: initParams.roomId
})

const subscribeQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  mobile: '',
  roomId: initParams.roomId,
  status: '',
  schoolId: '',
  subscribeTime: [],
  isPage: '' // 是否分页
})

const closeDialog = () => {
  dialogFormVisible.value = false
}

const activeName = ref('first')

// 锁定关闭空间：弹框数据
const dialog = reactive({
  visible: false,
  reason: '',
  lockDate: undefined as Date | undefined,
  actionType: '' as 'close' | 'lock' // 记录操作类型
});

// 处理标签页点击事件
const handleTabClick = (tab) => {
  switch (tab.props.name) {
    case 'first':
      getList();
      break;
    case 'second':
      getBanList();
      break;
    case 'third':
      getPasswordList();
      break;
    case 'fourth':
      getOpenList();
      break;
    case 'fifth':
      getSubscribeList();
      schoolApi.getSimpleList().then(response => {
        schools.value = response;
      });
      break;
  }
};

function onOpen(message: string, bol: boolean) {
  useConfirm(message, () => {
    let ids = [];
    if (!bol) {
      ids.push(initParams.roomId)
    }
    roomApi.open(bol ? [] : ids).then(() => {
      getRoomDetail().finally(() => useMessage("开启成功"));
    });
  })
}

function onRemote() {
  useConfirm("确认对所选琴房进行开门操作?", () => {
    let ids = [];
    ids.push(initParams.roomId);
    roomApi.remote(ids).then(() => {
      getRoomDetail().finally(() => useMessage("请求已发送"));
    });
  })
}

function onClose() {
  dialog.reason = ''; // 重置原因
  dialog.lockDate = undefined; // 重置锁定时间
  dialog.actionType = 'close'; // 设置操作类型
  dialog.visible = true; // 显示弹框
  dialogFormRef.value?.resetFields();
  // 保存状态
  dialog['action'] = () => {
    let ids = [];
    ids.push(initParams.roomId);
    roomApi.close({
        roomIds: ids,
        updateReason: dialog.reason
      }
    ).then(() => {
      useMessage("关闭成功");
    });
  }
}

function handleExclusiveEdit(row) {
  exclusiveDialog.value.exclusiveVisible = true;
  exclusiveDialog.value.id = row.id;
  if (row.availableStartDate && row.availableEndDate) {
    exclusiveDialog.value.dateTime = [row.availableStartDate, row.availableEndDate];
  } else {
    exclusiveDialog.value.dateTime = [];
  }

  exclusiveDialog.value.availableWeek = row.availableWeek ? JSON.parse(row.availableWeek) : [];
  // 回显可使用时间段
  const jsonString = row.availableTime.replace(/(\d{2}:\d{2})/g, '"$1"');
  // 解析为 JavaScript 数组
  const availableTimeArray = JSON.parse(jsonString);
  // 映射数据到 timeRangesLocal 以回显
  timeRangesLocal.value = availableTimeArray.map(timeRange => [timeRange[0], timeRange[1]]);
}

// 专属空间禁用日期新增
function handleExclusiveBanAdd() {
  exclusiveBanDialog.value.exclusiveBanVisible = true;
}

// 专属空间密码新增
function handleExclusivePasswordAdd() {
  exclusivePasswordDialog.value.exclusivePasswordVisible = true;
}

// 导入
function handleImport() {
  importDialog.value.importVisible = true;
}

// 导入学生excel
function handleStuImportExcel() {
  importStuFormRef.value.open(initParams.roomId);
}

// 导入教师excel
function handleTeaImportExcel() {
  importTeaFormRef.value.open(initParams.roomId);
}

const fetchOptions = async (type) => {
  memberOptions.value = await memberApi.listByMemberType(type);
};

function handleExclusiveDelete(row) {
  useConfirm(t("common.delMessage"), async () => {
    await roomExclusiveApi.deleteExclusive(row.id);
    getList().finally(() => useMessage(t('common.delSuccess')));
  });
}

// 删除专属空间禁用信息
function handleBanDelete(row) {
  useConfirm(t("common.delMessage"), async () => {
    await roomExclusiveBanApi.deleteExclusiveBan(row.id);
    getBanList().finally(() => useMessage(t('common.delSuccess')));
  });
}

// 删除专属空间密码
function handleExclusivePasswordDelete(row) {
  useConfirm(t("common.delMessage"), async () => {
    await roomPasswordApi.deleteExclusivePassword(row.id);
    getPasswordList().finally(() => useMessage(t('common.delSuccess')));
  });
}

function onLock() {
  dialog.reason = ''; // 重置原因
  dialog.lockDate = undefined; // 重置锁定时间
  dialog.actionType = 'lock'; // 设置操作类型
  dialog.visible = true; // 显示弹框
  dialogFormRef.value?.resetFields();
  // 保存状态
  dialog['action'] = () => {
    roomApi.lock({
      ids: initParams.roomId,
      date: dialog.lockDate,
      updateReason: dialog.reason // 传递原因
    }).then(() => {
      onCancel();
      useMessage("锁定成功");
    });
  }
}

function onCancel() {
  lock.value.visible = false;
  lock.value.date = undefined;
}


const handleQuery = () => {
  queryParams.pageNo = 1
  getList();
}

const handleOpenQuery = () => {
  openQueryParams.pageNo = 1
  getOpenList();
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const resetOpemQuery = () => {
  openQueryFormRef.value.resetFields()
  handleOpenQuery()
}

const handleSubscribeQuery = () => {
  subscribeQueryParams.pageNo = 1;
  getSubscribeList();
}

const resetSubscribeQuery = () => {
  subscribeQueryFormRef.value.resetFields();
  handleSubscribeQuery();
}

const getList = async () => {
  loading.value = true
  try {
    const exclusiveListData = await roomExclusiveApi.getPage(queryParams)
    list.value = exclusiveListData.list
    total.value = exclusiveListData.total
  } finally {
    loading.value = false
  }
}

// 获取禁用日期列表
const getBanList = async () => {
  banLoading.value = true;
  try {
    const banListData = await roomExclusiveBanApi.getBanDatePage(baseQueryParams)
    banList.value = banListData.list
    banTotal.value = banListData.total
  } finally {
    banLoading.value = false
  }
}

// 获取密码列表
const getPasswordList = async () => {
  passwordLoading.value = true;
  try {
    const passwordListData = await roomPasswordApi.getPasswordDatePage(baseQueryParams)
    passwordList.value = passwordListData.list
    passwordTotal.value = passwordListData.total
  } finally {
    passwordLoading.value = false
  }
}

// 获取开门记录列表
const getOpenList = async () => {
  openLoading.value = true;
  try {
    const openListData = await roomExclusiveOpenApi.getOpenPage(openQueryParams)
    openList.value = openListData.list
    openTotal.value = openListData.total
  } finally {
    openLoading.value = false
  }
}

// 获取今日订单列表
const getSubscribeList = async () => {
  subscribeLoading.value = true;
  try {
    subscribeQueryParams.isPage = 1;
    const subscribeListData = await subscribeApi.getTodaySubscribePage(subscribeQueryParams)
    subscribeList.value = subscribeListData.list
    subscribeTotal.value = subscribeListData.total
  } finally {
    subscribeLoading.value = false
  }
}

// 批量取消预约
function selectionChange(list: Array<any>) {
  selectKeys.value = [];
  list.forEach((item) => selectKeys.value.push(item.id));
  multipleSelection.value = list;
}

const cancel = () => {
  if (isEmpty(selectKeys.value)) return;

  useConfirm("确认对所选预约单取消预约?", () => {
    subscribeApi.cancelBatch(selectKeys.value).then(() => {
        getList();
        useMessage("取消成功", "success")
      }
    )
  })
}

/**
 * 基本信息
 */
const getRoomDetail = async () => {
  const roomDetail = await roomApi.getObj(initParams.roomId)
  roomDetails.value = [];
  roomDetails.value.push(roomDetail);
  if (roomDetail.status === 3) {
    isClose.value = true;
  }
  if (roomDetail.status === 4) {
    isLock.value = true;
  }
  if (roomDetail.supplierId == 1 || roomDetail.supplierId == 3) {
    isDateTimeRequire.value = true;
  }
}

function handleDialogSubmit() {
  if (dialog.reason.trim() === '') {
    useMessage('请输入原因');
    return;
  }
  if (dialog.actionType === 'lock' && !dialog.lockDate) {
    useMessage('请选择锁定时间');
    return;
  }
  dialog['action']();
  dialog.visible = false;
}

function handleDialogCancel() {
  dialog.lockDate = undefined;
  dialog.visible = false;
  dialog.reason = '';
}

const importFormRules = reactive({
  memberType: [{required: true, message: '用户类型不能为空', trigger: ['blur', 'change']}],
  memberIds: [{required: true, message: '用户不能为空', trigger: ['blur', 'change']}],
})

const passwordFormRules = reactive({
  password:[{required:true,message:'请输入密码',trigger: ['blur','change']},
            {min:6,max:6,message: '密码必须为6位',trigger: ['blur','change']}],
  dateTime:{required: isDateTimeRequire, message: '请输入密码有效期', trigger: ['blur', 'change']}
})

const handleSubscribeExport = () => {
  useConfirm(t("common.exportMessage"), async () => {
    exportLoading.value = true
    try {
      if (subscribeList.value.length == 0) {
        useMessage("没有可导出数据", "warning");
        return;
      }
      const exportData = multipleSelection.value.length > 0 ? multipleSelection.value
        : await useSubscribeApi().getTodaySubscribeNoPage(subscribeQueryParams);
      const formatData = exportData.map(formatSubData)
      // 创建工作簿
      const wb = XLSX.utils.book_new();
      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(formatData);
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, "选中数据");

      // 生成文件
      XLSX.writeFile(wb, "今日预约订单数据.xlsx");
    } finally {
      exportLoading.value = false
    }
  });
}

const formatSubData = (item) => {
  console.log(item)
  return {
    "预约人": item.memberName,
    "归属学校": item.schoolName,
    "手机号": item.mobile,
    "类型": item.type == 0 ? "学生" : "老师",
    "琴房类型": item.roomTypeName,
    "教学楼": item.buildingName,
    "楼层": item.floor,
    "房间号": item.number,
    "预约时间": formatDateTime(item.startTime),
    "预约时长": item.keepTime,
    "实际时长": item.actualTime,
    "预约状态": getSubStatus(item.status),
    "创建时间": formatDateTime(item.createTime)
  }
}

//时间戳格式化为时间
const formatDateTime = (timestamp: any) => {
  const formattedDate = new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false, // 使用 24 小时制
  }).format(new Date(timestamp));
  return formattedDate;
}

const getSubStatus = (status: any) => {
  let subStatus = '';
  switch (status) {
    case 1:
      subStatus = '未开始';
      break;
    case 2:
      subStatus = '待签到';
      break;
    case 3:
      subStatus = '进行中';
      break;
    case 4:
      subStatus = '已完成';
      break;
    case 5:
      subStatus = '已取消';
      break;
    case 6:
      subStatus = '爽约';
      break;
    default:
      subStatus = '未知';
  }
  return subStatus;
}

/** 初始化 **/
onMounted(async () => {
  await getRoomDetail();
  await getList();
})
</script>

<style>
.tabs-container {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

.full-width-tabs {
  width: 100%;
  height: 100%;
}

.button-container {
  display: flex;
  flex-wrap: wrap; /* 允许按钮换行 */
  gap: 5px; /* 按钮之间的间距 */
  justify-content: center; /* 按钮在水平方向上居中 */
  align-content: center; /* 按钮在垂直方向上居中 */
  align-items: center; /* 按钮在网格内垂直居中 */
}

.button-container .el-button {
  flex: 1 1 80px; /* 按钮宽度自适应 */
  max-width: 75px; /* 设置按钮最大宽度 */
}

.time-picker-wrapper {
  display: flex;
  flex-direction: column;
  gap: 10px; /* Gap between time picker items and add button */
}

.time-picker-item {
  display: flex;
  align-items: center;
  gap: 10px; /* Gap between time picker and delete button */
}

.time-picker {
  flex: 1; /* Allow time picker to take available space */
}

.delete-button {
  margin-left: 10px; /* Space between time picker and delete button */
}

.add-button {
  align-self: flex-start; /* Align add button to start of container */
}

.operation-buttons {
  display: flex;
  gap: 8px; /* 控制按钮之间的间距 */
  justify-content: center;
}
</style>
